package com.peanut.baby.mvp.ask;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.http.ApiException;
import com.peanut.baby.model.Photo;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.mvp.AddPhotoGridAdapter;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.util.TagUtil;
import com.peanut.baby.widget.UnScrollGridView;
import com.peanut.devlibrary.RequestResult;
import com.peanut.devlibrary.picker.ImageConfig;
import com.peanut.devlibrary.picker.PhotoPickerActivity;
import com.peanut.devlibrary.picker.PhotoPreviewActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/7/20.
 */

public class AskActivity extends BaseMvpActivity implements TitleLayout.OnTitleClickListener,
        AddPhotoGridAdapter.OnPhotoDeleteListener,
        AdapterView.OnItemClickListener,
        AskContract.View,
        View.OnClickListener {
    private static final String TAG = AskActivity.class.getSimpleName();
    private static final int MAX_PHOTO_NUM = 1;
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.ask_type)
    TextView askType;
    @BindView(R.id.ask_type_container)
    LinearLayout askTypeContainer;
    @BindView(R.id.ask_title)
    EditText askTitle;
    @BindView(R.id.ask_describe)
    EditText askDescribe;
    @BindView(R.id.ask_submit)
    TextView askSubmit;
    private AddPhotoGridAdapter adapter;
    private List<Photo> photos;


    @BindView(R.id.ask_photo_grid)
    UnScrollGridView askPhotoGrid;

    private AskPresenter presenter;

    private UploadConf  uploadConfig;

    /**
     * @param ctx
     */
    public static void start(Context ctx) {
        ctx.startActivity(new Intent(ctx, AskActivity.class));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ask);
        ButterKnife.bind(this);
        initialViews();
        presenter = new AskPresenter(this,this);
    }

    private void initialViews() {
        title.setTitle("提问");
        title.setOnTitleClickedListener(this);

        askTypeContainer.setOnClickListener(this);
        askSubmit.setOnClickListener(this);

        photos = new ArrayList<>();

        Photo addFlag = new Photo();
        addFlag.url = Photo.FLAG_ADD;
        photos.add(addFlag);

        adapter = new AddPhotoGridAdapter(this, photos);
        adapter.setOnPhotoDeleteListener(this);
        askPhotoGrid.setAdapter(adapter);
        askPhotoGrid.setOnItemClickListener(this);

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {

    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onPhotoDelete(int position) {
        photos.remove(position);
        //if size < MAX_PHOTO_SIZE, ADD_FLAG
        if (photos.size() < MAX_PHOTO_NUM) {
            Photo addFlag = new Photo();
            addFlag.url = Photo.FLAG_ADD;
            photos.add(addFlag);
        }
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Photo bean = (Photo) adapter.getItem(position);
        if (bean.url.equals(Photo.FLAG_ADD)) {
            presenter.checkPermissionBeforeSelectPhoto(AskActivity.this);
        } else {
            Log.d(TAG, "on preview photos " + position);
            PhotoPreviewActivity.start(AskActivity.this, getPreviewList(), position);
        }
    }

    /**
     * get list of images for preview
     *
     * @return
     */
    private ArrayList<String> getPreviewList() {
        ArrayList<String> previews = new ArrayList<>();
        for (int i = 0; i < photos.size(); i++) {
            if (!TextUtils.isEmpty(photos.get(i).url)) {
                if (!photos.get(i).url.equals(Photo.FLAG_ADD)) {
                    previews.add(photos.get(i).url);
                }
            } else {
                if (!TextUtils.isEmpty(photos.get(i).path)) {
                    previews.add(photos.get(i).path);
                }
            }
        }
        Log.d(TAG, "getPreviewList photos " + (previews == null ? "null" : " size " + previews.size()));
        return previews;
    }


    @Override
    public void onPermissionGranted(List<String> grantPermissions) {
        int realPhotoSize = photos.size();
        if (photos.get(photos.size() - 1).url.equals(Photo.FLAG_ADD)) {
            realPhotoSize = realPhotoSize - 1;
        }
        PhotoPickerActivity.startForResult(AskActivity.this, MAX_PHOTO_NUM - realPhotoSize, true, PhotoPickerActivity.MODE_MULTI, new ImageConfig());
    }

    @Override
    public void onPermissionDenied(List<String> grantPermissions) {
        showToast("请到设置中打开文件权限后再上传图片");
    }

    @Override
    public void onPictureUploadFinished(boolean success, String failReason, UploadConf successConfig) {
        dismissProgressDialog();
        if(success){
            this.uploadConfig = successConfig;

            //only one picture,make it easy
            if (photos.get(photos.size() - 1).url.equals(Photo.FLAG_ADD)) {
                photos.remove(photos.size() - 1);
            }

            Photo photo = new Photo();
            photo.path = uploadConfig.localPath;
            photo.url = uploadConfig.getResultFullUrl();
            photos.add(photo);

            // if size > MAX_PHOTO_SIZE,
            if (photos.size() > MAX_PHOTO_NUM) {
                photos = photos.subList(0, MAX_PHOTO_NUM);
            }
            //if size < MAX_PHOTO_SIZE, ADD_FLAG
            if (photos.size() < MAX_PHOTO_NUM) {
                Photo addFlag = new Photo();
                addFlag.url = Photo.FLAG_ADD;
                photos.add(addFlag);
            }

            adapter.notifyDataSetChanged();

        }else{
            this.uploadConfig = null;
        }
    }

    @Override
    public void onSubmitQuestionSuccess() {
        dismissProgressDialog();
        showToast("提问成功");
        finish();
    }

    @Override
    public void onRequestFailed(String code,String reason) {
        dismissProgressDialog();
        if(!ApiException.isApiException(code)){
            showToast(reason);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RequestResult.REQUEST_CODE_PHOTOS:
                ArrayList<String> _photos = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                onPickPhotoResult(_photos);
                break;
        }
    }

    private void onPickPhotoResult(ArrayList<String> result) {
        Log.d(TAG, "onPickPhotoResult _photos.size: " + (result == null ? "null" : "size:" + result.size()));
        showProgressDialog("正在上传图片...",false);
        presenter.compressAndUploadPicture(result.get(0));

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ask_type_container:
                new BaseDialog().showListDialog(this, "请选择类型", TagUtil.getTypeList(), new BaseDialog.OnListItemSelectedListener() {
                    @Override
                    public void onListItemSelected(String value) {
                        askType.setText(value);
                    }
                });
                break;
            case R.id.ask_submit:
                if(InitManager.getInstance().getUser() == null){
                    LoginActivity.startForResult(this);
                    return;
                }
                if(StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)){
                    BindMobileActivity.startForResult(this);
                    return;
                }

                submitQuestion();
                break;
        }
    }

    /**
     *
     */
    private void submitQuestion(){
        Log.d(TAG,"submitQuestion");
        String type = askType.getText().toString();
        String title = askTitle.getText().toString().trim();
        String desc = askDescribe.getText().toString().trim();
        if(StringUtil.isNullOrEmpty(type)){
            showToast("请选择问题类型");
            return;
        }
//        if(StringUtil.isNullOrEmpty(title)){
//            showToast("请填写问题标题");
//            return;
//        }
        if(StringUtil.isNullOrEmpty(desc)){
            showToast("请填写问题描述");
            return;
        }
        showProgressDialog("请稍后...",false);
        presenter.submitQuestion(type,title,desc,uploadConfig == null?"":uploadConfig.getResultFullUrl());

    }

}
